//
//  TravelPlugin.m
//  QYTravelV3
//
//  Created by xdzhangm on 2017/1/6.
//
//

#import "TravelPlugin.h"
#import "PhotoBroswerVC.h"

@implementation TravelPlugin
- (void)pluginInitialize 
{
    
}
- (void)showImages:(CDVInvokedUrlCommand *)command
{
    CDVPluginResult* pluginResult = nil;
    NSString* echo = [command.arguments objectAtIndex:0];
    
    if (echo != nil && [echo length] > 0) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:echo];
    } else {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
    }
    if(command.arguments && command.arguments.count > 0)
    {
        NSString *indexStr = command.arguments[0];
        NSInteger index = 0;
        NSInteger urlMinLen = 3;
        if(indexStr && indexStr.length <= urlMinLen)
        {
            index = [indexStr integerValue];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [PhotoBroswerVC show:self.viewController type:PhotoBroswerVCTypeModal index:index photoModelBlock:^NSArray *{
                NSMutableArray *modelsM = [NSMutableArray array];
                for (NSUInteger i = 0; i < command.arguments.count; i++)
                {
                    NSString *url = [command.arguments objectAtIndex:i];
                    if(url && url.length > urlMinLen)
                    {
                        PhotoModel *pbModel = [[PhotoModel alloc] init];
                        pbModel.mid = i + 1;
                        url = [self utf8String:url];
                        pbModel.image_HD_U = url;
                        pbModel.mid = [pbModel.image_HD_U hash];
                        [modelsM addObject:pbModel];
                    }
                }
                return modelsM;
            }];
        });
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void)exitApp:(CDVInvokedUrlCommand*)command
{
    [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
}

- (void)updateVersion:(CDVInvokedUrlCommand*)command
{
    [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
}

- (NSString *) utf8String:(NSString *)url
{
    return [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

- (void)dail:(CDVInvokedUrlCommand *)command
{
    if(!command.arguments.count)
    {
        return;
    }
    NSString *phoneNumber = [command.arguments objectAtIndex:0];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", phoneNumber]]];
}

- (void)openExternalUrl:(CDVInvokedUrlCommand*)command
{
    if(!command.arguments.count)
    {
        return;
    }
     NSString *link = [command.arguments objectAtIndex:0];
     if(!link.length)
     {
         return;
     }
     NSURL *linkUrl = [NSURL URLWithString:link];
     if(!linkUrl)
     {
         return;
     }
     [[UIApplication sharedApplication] openURL:linkUrl];
}
@end
